package com.zyao89.view.zweb.views;

import com.alibaba.fastjson.JSONObject;
import com.zyao89.view.zweb.exceptions.ZWebException;
import com.zyao89.view.zweb.javascript.ZJavaScriptEx;
import com.zyao89.view.zweb.utils.JsCallJava;
import com.zyao89.view.zweb.utils.JsUtils;
import ohos.agp.components.AttrSet;
import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.JsCallback;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.app.Context;

import java.util.HashMap;

/**
 * @author Zyao89
 * 2017/11/13.
 */
public class WebViewEx extends WebView {
    private final HashMap<String, JsCallJava> mJsInterfaceMap = new HashMap<String, JsCallJava>();
    private FixedOnReceivedTitle mFixedOnReceivedTitle;

    public WebViewEx(Context context) {
        super(context);
        init(context);
    }

    public WebViewEx(Context context, AttrSet attrs) {
        super(context, attrs);
        init(context);
    }


    private void init(Context context) {
        mFixedOnReceivedTitle = new FixedOnReceivedTitle();
        getWebConfig().setViewPortFitScreen(true);
    }

    public final void setBrowserAgent(BrowserAgentEx browserAgent) {
        browserAgent.setFixedOnReceivedTitle(mFixedOnReceivedTitle);
        super.setBrowserAgent(browserAgent);
    }

    public final void setWebAgent(WebAgentEx webAgent) {
        webAgent.setFixedOnReceivedTitle(mFixedOnReceivedTitle);
        super.setWebAgent(webAgent);
    }

    @Override
    public void onStop() {
        setVisibility(HIDE);
        mJsInterfaceMap.clear();
        super.onStop();
    }

    @Override
    @Deprecated
    public void setWebAgent(WebAgent webAgent) {
        throw new ZWebException("WebAgent is Deprecated...");
    }

    @Override
    @Deprecated
    public void setBrowserAgent(BrowserAgent browserAgent) {
        throw new ZWebException("BrowserAgent is Deprecated...");
    }


    public void addJavascriptInterface(Object interfaceObj, String interfaceName) {
        if (interfaceName.isEmpty()) {
            return;
        }

        super.addJsCallback(interfaceName, new JsCallback() {
            @Override
            public String onCallback(String s) {
                JSONObject dataJson = JsUtils.json2Obj(s);
                String frameworkUUID = dataJson.getString("FrameworkUUID");
                String methodName = dataJson.getString("szMethodName");
                String oData = dataJson.getString("oData");
                if (methodName.equals("onMessage")) {
                    ((ZJavaScriptEx) interfaceObj).onMessage(frameworkUUID, oData);
                } else if (methodName.equals("onCreated")) {
                    ((ZJavaScriptEx) interfaceObj).onCreated(frameworkUUID, oData);
                }
                return null;
            }
        });
    }
}
